import WebsocketHeartbeatJs from "websocket-heartbeat-js";
import Vue from "vue";
import store from "@/store/store";
let websocketHeartbeatJs;
let tradeWSList = []; // 交易ws列表数据
let StockData;
let zixuanSub;
let wsMarket;
// 推送参数设置
const setOption = () => {
  const protocol = window.location.protocol == "http:" ? "ws://" : "wss://";
  const options = {
    url:
      protocol + window.g.wsURL + "?token=" + sessionStorage.getItem("token"),
    pingTimeout: 10000,
    pongTimeout: 12000,
    reconnectTimeout: 5000,
    pingMsg: '{"action":"PING"}',
  };
  let websocketHeartbeatJs = new WebsocketHeartbeatJs(options);
  return websocketHeartbeatJs;
};
const getStockData = (val)=> {
  StockData = val
}
const getZixuanSub = (val)=> {
  zixuanSub = val;
}
const getWsMarket = (val)=> {
  wsMarket = val;
}
// 将逐笔，盘口，行情加入队列
const queue = (val) => {
  let que = [];
  let val1 = {
    market: val.market,
    securityType: val.securityType,
    action: "Q",
    symbol: val.symbol,
  };
  que.push(val1);
  let val2 = JSON.parse(JSON.stringify(val1));
  val2.action = "T";
  que.push(val2);
  let val3 = JSON.parse(JSON.stringify(val1));
  val3.action = "O";
  que.push(val3);
  store.dispatch("SetSymbolSub", JSON.stringify(que));
  return que;
};
const getList = (val, level) => {
  let list = [];
  // 沪深行情大于lv1等级实时推送
  if (level.CN.level > 1) {
    // 当前股票是沪深的股票
    if (val.market == "SSE" || val.market == "SZSE") {
      list = queue(val);
      return list;
    }
  }
  // 港股行情等级大于LV1实时推送
  if (level.HK.level > 1) {
    if (val.market == "HKEX") {
      list = queue(val);
      return list;
    }
  }
  // 美股行情等级大于LV0实时推送
  if (level.US.level > 0) {
    if (val.market == "US") {
      list = queue(val);
      return list;
    }
  }
  return list;
};
// 拼接取消订阅数据类型
const SubData = (val) => {
  if (val == "") return;
  if (typeof val == "string") val = JSON.parse(val);
  let values = [...val];
  let items = "";
  for (let i = 0; i < values.length; i++) {
    let objJoin = "";
    for (let key in values[i]) {
      if (key != "symbol") objJoin = objJoin + values[i][key] + "|";
      else objJoin = objJoin + values[i][key];
    }
    if (i != values.length - 1) items = items + objJoin + ",";
    else items = items + objJoin;
  }
  return items;
};
// ws订阅类型过滤器
const wsFifters = (action, val,data) => {
  // T:交易数据 Q:行情数据 O:盘口数据
  if (val == "") return;
  let vals = val.split("|");
  // Q:行情数据
  if (action == "Q") {
    if (vals[1] != 1) {
      if (data) {
        for (let item of data) {
          // 如果股票代码与大盘推送列表相同放入推送列表
          if (item.symbol == vals[3]) {
            store.dispatch("SetDaPanDetail", JSON.stringify(vals));
            break;
          }
        }
      }
    }
    // 当前股票推送
    if(JSON.stringify(StockData) == "{}") return;
    if (
      StockData.symbol == vals[3] &&
      StockData.market == vals[0] &&
      StockData.securityType == vals[1]
      ) {
        store.dispatch("SetQuotation", JSON.stringify(vals));
      }
      // 自选股票推送
      if (zixuanSub) {
        // 按自选顺序将股票信息存入自选列表
        let zixuan = JSON.parse(zixuanSub);
        for (let i = 0; i < zixuan.length; i++) {
          // 如果当前过滤值与自选列表股票代码相同存入自选队列
          if (
            zixuan[i].symbol == vals[3] &&
            zixuan[i].market == vals[0] &&
            zixuan[i].securityType == vals[1]
            ) {
          Vue.nextTick(() => {
            Vue.set(zixuan[i], "latestPrice", vals[4]);
            Vue.set(zixuan[i], "high", vals[5]);
            Vue.set(zixuan[i], "open", vals[6]);
            Vue.set(zixuan[i], "low", vals[7]);
            Vue.set(zixuan[i], "close", vals[8]);
            Vue.set(zixuan[i], "volume", vals[9]);
            Vue.set(zixuan[i], "amount", vals[10]);
            Vue.set(zixuan[i], "gain", (vals[4] - vals[8]) / vals[8]);
            store.dispatch("SetZixuanList", JSON.stringify(zixuan));
          });
          break;
        }
      }
    }
    // 市场股推送
    if (wsMarket) {
      // 将市场股票信息存入市场列表列表
      let marketList = JSON.parse(wsMarket);
      for (let i = 0; i < marketList.length; i++) {
        // 如果当前过滤值与自选列表股票代码相同存入自选队列
        if (
          marketList[i].symbol == vals[3] &&
          marketList[i].market == vals[0] &&
          marketList[i].securityType == vals[1]
        ) {
          Vue.nextTick(() => {
            Vue.set(marketList[i], "latestPrice", vals[4]);
            Vue.set(marketList[i], "high", vals[5]);
            Vue.set(marketList[i], "open", vals[6]);
            Vue.set(marketList[i], "low", vals[7]);
            Vue.set(marketList[i], "close", vals[8]);
            Vue.set(marketList[i], "volume", vals[9]);
            Vue.set(marketList[i], "amount", vals[10]);
            Vue.set(marketList[i], "gain", (vals[4] - vals[8]) / vals[8]);
            store.dispatch("SetWsMarketInfo", JSON.stringify(marketList));
          });
          break;
        }
      }
    }
  } else if (action == "T") {
    // 交易推送数据
    if (StockData.symbol == vals[3] && StockData.market == vals[0]) {
      if (tradeWSList.length == 20) {
        let tradeData = JSON.stringify(tradeWSList);
        store.dispatch("SetTransaction", tradeData);
        tradeWSList = [];
      } else tradeWSList.unshift(vals);
    }
  } 
  else if (action == "O") {
    store.dispatch("SetPankou", JSON.stringify(vals));
  }
};
const websock = (data) => {
  // 推送初始化
  websocketHeartbeatJs = setOption();
  // 得到对应格式的WS订阅数据列表
  // 取消订阅
  websocketHeartbeatJs.delSubscribe = (val) => {
    // 发送关闭请求
    let items = SubData(val);
    let value = {
      action: "DELSUBSCRIBE",
      symbols: items,
    };
    websocketHeartbeatJs.send(JSON.stringify(value));
    tradeWSList = [];
  };
  // 打开ws时的回调
  websocketHeartbeatJs.onopen = () => {
    // 得到当前股票订阅格式
    // websocketHeartbeatJs.webSocketOpen(data);
  };
  // 接收到数据，过滤数据
  websocketHeartbeatJs.onmessage = (e) => {
    e = JSON.parse(e.data);
    // 如果返回连接成功，开始订阅
    if (e.action == "OPENED") {
      websocketHeartbeatJs.webSocketOpen(data);
      console.log("onmessage");
    }
    if (e.code == 201) return websocketHeartbeatJs.close();
    if (e.data !== undefined) {
      if (e.action == "DELSUBSCRIBE") {
        // 如果取消全部订阅，关闭连接
        return;
      }
      // 分发数据
      wsFifters(e.action, e.data,data);
    }
  };
  // 发送订阅请求
  websocketHeartbeatJs.webSocketOpen = (val) => {
    if (val.length <= 0) return;
    let items = SubData(val);
    let value = {
      action: "SUBSCRIBE",
      symbols: items,
    };
    websocketHeartbeatJs.send(JSON.stringify(value));
    console.log(value, "connect success");
  };
  websocketHeartbeatJs.onreconnect = (e) => {
    console.log("reconnecting...");
  };
  websocketHeartbeatJs.onclose = (e) => {
    console.log("connect close");
  };
  store.dispatch("SETHEARTBEAT", websocketHeartbeatJs);
};
export { websock, getList, getStockData, getZixuanSub, getWsMarket };
